<template>
  <lay-table :columns="columns" :data-source="OriginList" :loading="loading" v-model:selected-keys="selectedKeys">
    <template v-slot:toolbar>
      <lay-button size="xs" type="primary" @click="changeAddVisible">新增</lay-button>
    </template>
    <template #status="{ row }">
      <lay-switch :model-value="row.status" @change="changeStatus($event, row)"></lay-switch>
    </template>
    <template v-slot:operator="{ row }">
      <lay-button size="xs" @click="update(row)" border="green" border-style="dashed">编辑</lay-button>
      <lay-popconfirm :content="row.resource_count === 0 ? '确定要删除吗？' : '不能删除！存在已关联资源!'" position="left"
        @confirm="remove(row)" @cancel="() => layer.msg('操作已取消！', { icon: 3, time: 1000 })">
        <lay-button size="xs" border="red" border-style="dashed" :disabled="row.resource_count !== 0">删除</lay-button>
      </lay-popconfirm>
    </template>
  </lay-table>

  <!-- 新增 ========================================== -->
  <lay-layer v-model="addVisible" :shade="false" :area="['500px', '']" :resize="true" :title="'新增起源'" :btn="addAction">
    <div style="padding: 20px;">
      <lay-form :model="newOrigin" ref="addOriginForm">
        <lay-form-item label="名称" prop="name" required>
          <lay-input v-model="newOrigin.name"></lay-input>
        </lay-form-item>
        <lay-form-item label="描述" prop="description">
          <lay-input v-model="newOrigin.description"></lay-input>
        </lay-form-item>
      </lay-form>
    </div>
  </lay-layer>

  <!-- 修改信息 ========================================== -->
  <lay-layer v-model="updateVisible" :shade="false" :area="['500px', '']" :resize="true" :title="'修改起源'"
    :btn="updateAction">
    <div style="padding: 20px;">
      <lay-form :model="updateOrigin" ref="updateOriginForm">
        <lay-form-item label="ID" prop="id">
          <lay-input v-model="updateOrigin.id" :disabled="true"></lay-input>
        </lay-form-item>
        <lay-form-item label="名称" prop="name" required>
          <lay-input v-model="updateOrigin.name"></lay-input>
        </lay-form-item>
        <lay-form-item label="描述" prop="description">
          <lay-input v-model="updateOrigin.description"></lay-input>
        </lay-form-item>
      </lay-form>
    </div>
  </lay-layer>
</template>

<script setup>
import { ref, reactive, onMounted, h } from 'vue';
import { layer } from '@layui/layui-vue';
import api from '@/api';

const loading = ref(true);
const selectedKeys = ref([]);

// 获取数据列表
const OriginList = ref([]);
async function getOriginList() {
  try {
    let response = await api.get('field/origin/list');
    OriginList.value = response.data;
    loading.value = false
  } catch (e) {
    console.error('获取起源列表失败', e);
  }
}


// 新增
const addVisible = ref(false);
const changeAddVisible = () => {
  addVisible.value = !addVisible.value;
}
const newOrigin = reactive({
  name: "",
  description: "",
})
const addOriginForm = ref();

const addOriginHandler = async () => {
  let response = await api.get('field/origin/add', {
    name: newOrigin.name,
    description: newOrigin.description
  });

  if (response.code === 200) {
    layer.msg(response.msg, { icon: 1, time: 1000 });
    getOriginList(); // 刷新起源列表
    addVisible.value = !addVisible.value;
  } else {
    layer.msg(response.msg, { icon: 2, time: 2000 });
  }
}

const addAction = ref([
  {
    text: "添加",
    callback: () => {
      if (addOriginForm.value.validate()) {
        addOriginHandler();
      } else {
        layer.msg("请填写完整信息！", { icon: 2, time: 2000 });
        return;
      }
    }
  },
  {
    text: "取消",
    callback: () => {
      layer.msg("操作已取消！", { icon: 3, time: 1000 });
      addVisible.value = !addVisible.value;
    }
  }
])


// 修改信息
const updateVisible = ref(false);
const updateOrigin = reactive({
  id: null,
  name: "",
  description: "",
})
const updateOriginForm = ref();

async function update(row) {
  console.log('@row:', row.id);
  updateOrigin.id = row.id;
  updateOrigin.name = row.name;
  updateOrigin.description = row.description;
  updateOrigin.status = row.status;
  updateVisible.value = !updateVisible.value;
}

const updateOriginHandler = async () => {
  let response = await api.get('field/origin/update', {
    id: updateOrigin.id,
    name: updateOrigin.name,
    description: updateOrigin.description,
    status: updateOrigin.status
  });

  if (response.code === 200) {
    layer.msg(response.msg, { icon: 1, time: 1000 });
    getOriginList(); // 刷新起源列表
  } else {
    layer.msg(response.msg, { icon: 2, time: 2000 });
  }
}

const updateAction = ref([
  {
    text: "保存",
    callback: () => {
      if (updateOriginForm.value.validate()) {
        updateOriginHandler();
        updateVisible.value = !updateVisible.value;
      } else {
        layer.msg("请填写完整信息！", { icon: 2, time: 2000 });
        return;
      }
    }
  },
  {
    text: "取消",
    callback: () => {
      layer.msg("操作已取消！", { icon: 3, time: 1000 });
      updateVisible.value = !updateVisible.value;
    }
  }
])

// 切换启用状态
const changeStatus = (isChecked, row) => {
  OriginList.value.forEach((item) => {
    if (item.id === row.id) {
      item.status = isChecked;
      updateOrigin.id = item.id;
      updateOrigin.name = item.name;
      updateOrigin.description = item.description;
      updateOrigin.status = item.status;
      updateOriginHandler();
    }
  })
}

// 删除
async function remove(row) {
  console.log('@row:', row.id);
  if (row.resource_count !== 0) {
    layer.msg('不能删除！存在已关联资源!', { icon: 2, time: 2000 });
    return;
  }
  const response = await api.get('field/origin/delete', { id: row.id });
  if (response.code === 200) {
    selectedKeys.value = [];
    getOriginList(); // 刷新起源列表
    console.log(`删除起源 ${row.id} 成功！`, response);
    layer.msg(response.msg, { icon: 1, time: 1000 })
  } else {
    layer.msg(response.msg, { icon: 2, time: 1000 })
  }
}


const columns = [
  // { fixed: "left", type: "checkbox", title: "复选" },
  { title: "ID", key: "id", width: "70px", align: 'center', sort: true },
  { title: "名称", key: "name", align: 'center', ellipsisTooltip: true, },
  { title: "描述", key: "description", align: 'center', ellipsisTooltip: true, },
  { title: "关联资源数量", key: "resource_count", align: 'center', ellipsisTooltip: true, },
  { title: "启用", key: "status", align: 'center', customSlot: "status" },
  { title: "操作", key: "operator", width: "100px", align: 'center', customSlot: "operator", fixed: "right", ignoreExport: true }
]

onMounted(() => {
  getOriginList();
});
</script>

<style scoped>
.layui-card-body {
  padding: 5px !important;
}
</style>